<template>
  <div class="my-shares-tab">
    <el-card class="shares-header">
      <div class="header-content">
        <div class="shares-info">
          <h3>我的分享</h3>
          <p>管理您分享的搭配</p>
        </div>
        <el-button type="primary" @click="shareNewOutfit">
          <el-icon><Plus /></el-icon>
          分享新搭配
        </el-button>
      </div>
    </el-card>

    <div class="shares-list" v-loading="loading">
      <div v-if="shares.length === 0" class="empty-state">
        <el-empty description="您还没有分享过搭配">
          <el-button type="primary" @click="shareNewOutfit">
            分享第一个搭配
          </el-button>
        </el-empty>
      </div>

      <div v-else class="shares-grid">
        <div 
          v-for="share in shares" 
          :key="share.id"
          class="share-item"
        >
          <el-card shadow="hover">
            <div class="share-image-container">
              <img 
                :src="share.outfit?.main_image || '/placeholder-outfit.png'" 
                :alt="share.outfit?.name"
                class="share-image"
              />
              <div class="share-status">
                <el-tag 
                  :type="share.is_public ? 'success' : 'info'"
                  size="small"
                >
                  {{ share.is_public ? '公开' : '私密' }}
                </el-tag>
              </div>
            </div>

            <div class="share-content">
              <h4 class="share-title">{{ share.outfit?.name }}</h4>
              <p v-if="share.caption" class="share-caption">{{ share.caption }}</p>
              
              <div class="share-stats">
                <div class="stat-item">
                  <el-icon><View /></el-icon>
                  <span>{{ share.view_count || 0 }} 浏览</span>
                </div>
                <div class="stat-item">
                  <el-icon><Star /></el-icon>
                  <span>{{ share.like_count || 0 }} 点赞</span>
                </div>
                <div class="stat-item">
                  <el-icon><ChatDotRound /></el-icon>
                  <span>{{ share.comment_count || 0 }} 评论</span>
                </div>
              </div>

              <div class="share-meta">
                <span class="share-platform" v-if="share.platform">
                  分享到: {{ getPlatformName(share.platform) }}
                </span>
                <span class="share-time">{{ formatDate(share.created_at) }}</span>
              </div>

              <div class="share-actions">
                <el-button size="small" @click="viewShare(share)">
                  查看详情
                </el-button>
                <el-button size="small" @click="editShare(share)">
                  编辑
                </el-button>
                <el-dropdown @command="handleShareAction">
                  <el-button size="small">
                    更多
                    <el-icon><ArrowDown /></el-icon>
                  </el-button>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item :command="`copy-${share.id}`">
                        复制链接
                      </el-dropdown-item>
                      <el-dropdown-item :command="`toggle-${share.id}`">
                        {{ share.is_public ? '设为私密' : '设为公开' }}
                      </el-dropdown-item>
                      <el-dropdown-item :command="`delete-${share.id}`" divided>
                        删除分享
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
            </div>
          </el-card>
        </div>
      </div>
    </div>

    <!-- 分页 -->
    <div class="pagination-wrapper" v-if="total > 0">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[12, 24, 48]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 编辑分享对话框 -->
    <el-dialog v-model="editDialogVisible" title="编辑分享" width="500px">
      <el-form :model="editForm" label-width="80px">
        <el-form-item label="标题">
          <el-input v-model="editForm.title" disabled />
        </el-form-item>
        <el-form-item label="描述">
          <el-input 
            v-model="editForm.caption" 
            type="textarea" 
            :rows="3"
            placeholder="分享一些想法..."
          />
        </el-form-item>
        <el-form-item label="可见性">
          <el-radio-group v-model="editForm.is_public">
            <el-radio :label="true">公开</el-radio>
            <el-radio :label="false">私密</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveEdit" :loading="saving">
          保存
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { socialAPI } from '@/api'

const loading = ref(false)
const saving = ref(false)
const editDialogVisible = ref(false)

const shares = ref([])
const currentPage = ref(1)
const pageSize = ref(12)
const total = ref(0)

const editForm = reactive({
  id: null,
  title: '',
  caption: '',
  is_public: true
})

const loadShares = async () => {
  try {
    loading.value = true
    // 这里应该调用获取用户分享列表的API
    // 暂时使用模拟数据
    const mockShares = [
      {
        id: 1,
        outfit: {
          id: 1,
          name: '春日休闲搭配',
          main_image: '/placeholder-outfit.png'
        },
        caption: '今天的穿搭分享，简约舒适的春日风格',
        is_public: true,
        view_count: 156,
        like_count: 23,
        comment_count: 8,
        platform: 'weibo',
        created_at: new Date().toISOString()
      }
    ]
    
    shares.value = mockShares
    total.value = mockShares.length
  } catch (error) {
    console.error('获取分享列表失败:', error)
    ElMessage.error('获取分享列表失败')
  } finally {
    loading.value = false
  }
}

const shareNewOutfit = () => {
  // 跳转到分享页面或打开分享对话框
  console.log('分享新搭配')
}

const viewShare = (share) => {
  console.log('查看分享详情:', share)
}

const editShare = (share) => {
  editForm.id = share.id
  editForm.title = share.outfit?.name || ''
  editForm.caption = share.caption || ''
  editForm.is_public = share.is_public
  editDialogVisible.value = true
}

const saveEdit = async () => {
  try {
    saving.value = true
    // 这里应该调用更新分享的API
    ElMessage.success('分享更新成功')
    editDialogVisible.value = false
    loadShares()
  } catch (error) {
    console.error('更新分享失败:', error)
    ElMessage.error('更新分享失败')
  } finally {
    saving.value = false
  }
}

const handleShareAction = async (command) => {
  const [action, shareId] = command.split('-')
  const share = shares.value.find(s => s.id == shareId)
  
  if (!share) return
  
  switch (action) {
    case 'copy':
      // 复制分享链接
      navigator.clipboard.writeText(`${window.location.origin}/share/${shareId}`)
      ElMessage.success('链接已复制到剪贴板')
      break
      
    case 'toggle':
      // 切换公开/私密状态
      try {
        share.is_public = !share.is_public
        ElMessage.success(`已设为${share.is_public ? '公开' : '私密'}`)
      } catch (error) {
        ElMessage.error('操作失败')
      }
      break
      
    case 'delete':
      // 删除分享
      try {
        await ElMessageBox.confirm('确定要删除这个分享吗？', '确认删除', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        shares.value = shares.value.filter(s => s.id !== share.id)
        ElMessage.success('分享删除成功')
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('删除失败')
        }
      }
      break
  }
}

const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
  loadShares()
}

const handleCurrentChange = (page) => {
  currentPage.value = page
  loadShares()
}

const getPlatformName = (platform) => {
  const platforms = {
    weibo: '微博',
    wechat: '微信',
    qq: 'QQ空间',
    douyin: '抖音'
  }
  return platforms[platform] || platform
}

const formatDate = (dateString) => {
  return new Date(dateString).toLocaleDateString('zh-CN')
}

onMounted(() => {
  loadShares()
})
</script>

<style scoped>
.my-shares-tab {
  space-y: 20px;
}

.shares-header {
  margin-bottom: 20px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.shares-info h3 {
  margin: 0 0 4px 0;
  color: #333;
}

.shares-info p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.shares-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 20px;
}

.share-item {
  width: 100%;
}

.share-image-container {
  position: relative;
  margin-bottom: 12px;
}

.share-image {
  width: 100%;
  height: 180px;
  object-fit: cover;
  border-radius: 8px;
}

.share-status {
  position: absolute;
  top: 8px;
  right: 8px;
}

.share-content {
  padding: 12px;
}

.share-title {
  margin: 0 0 8px 0;
  font-size: 16px;
  color: #333;
  font-weight: 600;
}

.share-caption {
  margin: 0 0 12px 0;
  font-size: 14px;
  color: #666;
  line-height: 1.5;
}

.share-stats {
  display: flex;
  gap: 16px;
  margin-bottom: 12px;
  padding-bottom: 12px;
  border-bottom: 1px solid #eee;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
  color: #666;
}

.share-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  font-size: 12px;
  color: #999;
}

.share-actions {
  display: flex;
  gap: 8px;
}

.empty-state {
  text-align: center;
  padding: 60px 20px;
}

.pagination-wrapper {
  margin-top: 40px;
  text-align: center;
}

@media (max-width: 768px) {
  .shares-grid {
    grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
    gap: 16px;
  }
  
  .header-content {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }
  
  .share-actions {
    flex-direction: column;
  }
}
</style>
